/*
 * @lc app=leetcode.cn id=2130 lang=cpp
 *
 * [2130] 链表最大孪生和
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution
{
public:
    ListNode *reverse(ListNode *p)
    {
        ListNode *head = NULL;
        while (p)
        {
            ListNode *next = p->next;
            p->next = head;
            head = p;
            p = next;
        }
        return head;
    }

    int pairSum(ListNode *head)
    {
        ListNode *p = head, *q = head;
        while (q != NULL)
        {
            p = p->next;
            q = q->next->next;
        }

        ListNode *tail = reverse(p);

        int ans = -1;
        while (tail != NULL)
        {
            ans = max(ans, tail->val + head->val);
            tail = tail->next;
            head = head->next;
        }

        return ans;
    }
};
// @lc code=end
